<?php
use \Config;
final class CacheException extends \Exception{}
final class Cache
{
    public function __construct()
    {
        throw new CacheException('這是獨體模式');
    }
    private static $instances = array();
    public static function instance()
    {
        Config::load('cache');
        $key = Config::get('cache.stash');
        if ( ! isset(self::$instances[$key]))
        {
            $namespace_class = 'Cache\\'.  ucwords($key);
            if (@class_exists($namespace_class))
            {
                self::$instances[$key] = new $namespace_class;
            }
            else
            {
                throw new CacheException("沒有此class[$namespace_class]");
            }
        }
        return self::$instances[$key];
    }
    
    //反射呼叫物件方法
    public static function __callStatic($method, $args)
    {
        return self::call($method, $args);
    }

    //反射呼叫單一物件方法
    private static function call($method, $args)
    {
        $o = self::instance();
        $callback = array($o, $method);
        if ( ! is_callable($callback)) {
            throw new CacheException(get_class($o)."::{$method} 不存在");
        }

        return call_user_func_array($callback, $args);
    }
}